package com.mgq.juc.design.alternate;

/**
 * @author MaGuangQi
 * 使用waitNotify来实现3个线程交替打印abc
 * @date 2021-12-17 13:41
 **/


public class WaitNotify {
    public static void main(String[] args) {
        WaitNotify waitNotify=new WaitNotify(1,5);
        //锁定是this,所以waitNotify应该只有一个实例
        new Thread(()->{
            waitNotify.print("a",1,2);
        },"t1").start();
        new Thread(()->{
            waitNotify.print("b",2,3);
        },"t2").start();
        new Thread(()->{
            waitNotify.print("c",3,1);
        },"t3").start();
    }

    /**
     *  线程         flag          下一个flag(用来控制下一个标记)
     *  a            1              2
     *  b            2              3
     *  c            3              1
     *
     *  思路, 首先每个线程对应一个flag,比如线程a flag=1时,打印a,线程b flag=2时,打印b,线程c flag=3时,打印c
     *  打印完后,让当前标记变为下一个等待标记
     * */


    //用来设置初始标记
    private int flag;
    //用于控制循环次数
    private int loopNumber;

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }

    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this) {
                while (waitFlag != this.flag) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //
                System.out.print(str);
                this.flag=nextFlag;
                this.notifyAll();
            }
        }

    }

}
